package com.aididi.filters;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Auther: zx.xu
 * @Description:    自定义gateway filter过滤器类
 *              需要实现GatewayFilter和Ordered接口
 */
@Slf4j
public class MyRequestGatewayFilter implements GatewayFilter,Ordered {
    private static final String REQUEST_TIME_BEGIN = "requestTimeBegin";

    /**
     *  filters(exchange,chain)相当于 “pre”类型的过滤器，chain.filter的内部类中的run()方法中相当于”post”过滤器
     *  chain.filter(exchange)之前的就是“pre”部分，之后的也就是then里边的是“post”部分
     * @param exchange
     * @param chain
     * @return  打印请求所消耗的时间
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        exchange.getAttributes().put(REQUEST_TIME_BEGIN,System.currentTimeMillis());
        return chain.filter(exchange).then(
                Mono.fromRunnable(() ->{
                    Long startTime = exchange.getAttribute(REQUEST_TIME_BEGIN);
                    if(null != startTime){
                        log.info(exchange.getRequest().getURI().getRawPath() +
                            ":" +(System.currentTimeMillis() - startTime + "ms"));
                    }
                })
        );
    }

    /**
     * 设置过滤器执行的优先级别，值越大则优先级越低
     * @return
     */
    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
